package com.isoft.airportsystem.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isoft.airportsystem.entity.system.Role;
import com.isoft.airportsystem.entity.system.RolePermission;
import com.isoft.airportsystem.entity.system.UserRole;
import com.isoft.airportsystem.mapper.system.RoleMapper;
import com.isoft.airportsystem.mapper.system.RolePermissionMapper;
import com.isoft.airportsystem.mapper.system.UserRoleMapper;
import com.isoft.airportsystem.service.system.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 角色服务实现类
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Page<Role> selectRolePage(Page<Role> page, Role role) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        if (role != null) {
            // 根据角色名称模糊查询
            if (StringUtils.hasText(role.getRoleName())) {
                queryWrapper.like(Role::getRoleName, role.getRoleName());
            }
            // 根据角色编码模糊查询
            if (StringUtils.hasText(role.getRoleCode())) {
                queryWrapper.like(Role::getRoleCode, role.getRoleCode());
            }
            // 根据状态查询
            if (role.getStatus() != null) {
                queryWrapper.eq(Role::getStatus, role.getStatus());
            }
        }
        // 只查询未删除的角色
        queryWrapper.eq(Role::getDelFlag, 0);
        // 按角色排序升序排序
        queryWrapper.orderByAsc(Role::getRoleSort);
        return page(page, queryWrapper);
    }

    @Override
    public List<Role> selectRoleList(Role role) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        if (role != null) {
            // 根据角色名称模糊查询
            if (StringUtils.hasText(role.getRoleName())) {
                queryWrapper.like(Role::getRoleName, role.getRoleName());
            }
            // 根据角色编码模糊查询
            if (StringUtils.hasText(role.getRoleCode())) {
                queryWrapper.like(Role::getRoleCode, role.getRoleCode());
            }
            // 根据状态查询
            if (role.getStatus() != null) {
                queryWrapper.eq(Role::getStatus, role.getStatus());
            }
        }
        // 只查询未删除的角色
        queryWrapper.eq(Role::getDelFlag, 0);
        // 按角色排序升序排序
        queryWrapper.orderByAsc(Role::getRoleSort);
        return list(queryWrapper);
    }

    @Override
    public List<Role> selectRolesByUserId(Long userId) {
        return baseMapper.selectRolesByUserId(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertRole(Role role, Long[] permissionIds) {
        // 设置默认值
        role.setCreateTime(LocalDateTime.now());
        role.setDelFlag(0);
        // 保存角色信息
        boolean result = save(role);
        // 保存角色权限关联信息
        if (result && permissionIds != null && permissionIds.length > 0) {
            insertRolePermission(role.getRoleId(), permissionIds);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRole(Role role, Long[] permissionIds) {
        // 设置更新时间
        role.setUpdateTime(LocalDateTime.now());
        // 更新角色信息
        boolean result = updateById(role);
        // 删除原有角色权限关联
        if (result) {
            LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RolePermission::getRoleId, role.getRoleId());
            rolePermissionMapper.delete(queryWrapper);
            // 保存新的角色权限关联信息
            if (permissionIds != null && permissionIds.length > 0) {
                insertRolePermission(role.getRoleId(), permissionIds);
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRoleById(Long roleId) {
        // 检查角色是否已分配给用户
        LambdaQueryWrapper<UserRole> userRoleQueryWrapper = new LambdaQueryWrapper<>();
        userRoleQueryWrapper.eq(UserRole::getRoleId, roleId);
        Long count = userRoleMapper.selectCount(userRoleQueryWrapper);
        if (count > 0) {
            throw new RuntimeException("角色已分配给用户，不能删除");
        }
        // 逻辑删除角色
        Role role = new Role();
        role.setRoleId(roleId);
        role.setDelFlag(1);
        role.setUpdateTime(LocalDateTime.now());
        boolean result = updateById(role);
        // 删除角色权限关联
        if (result) {
            LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RolePermission::getRoleId, roleId);
            rolePermissionMapper.delete(queryWrapper);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRoleByIds(Long[] roleIds) {
        // 检查角色是否已分配给用户
        LambdaQueryWrapper<UserRole> userRoleQueryWrapper = new LambdaQueryWrapper<>();
        userRoleQueryWrapper.in(UserRole::getRoleId, Arrays.asList(roleIds));
        Long count = userRoleMapper.selectCount(userRoleQueryWrapper);
        if (count > 0) {
            throw new RuntimeException("角色已分配给用户，不能删除");
        }
        // 批量逻辑删除角色
        List<Role> roleList = new ArrayList<>();
        for (Long roleId : roleIds) {
            Role role = new Role();
            role.setRoleId(roleId);
            role.setDelFlag(1);
            role.setUpdateTime(LocalDateTime.now());
            roleList.add(role);
        }
        boolean result = updateBatchById(roleList);
        // 批量删除角色权限关联
        if (result) {
            LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(RolePermission::getRoleId, Arrays.asList(roleIds));
            rolePermissionMapper.delete(queryWrapper);
        }
        return result;
    }

    @Override
    public boolean updateRoleStatus(Long roleId, Integer status) {
        Role role = new Role();
        role.setRoleId(roleId);
        role.setStatus(status);
        role.setUpdateTime(LocalDateTime.now());
        return updateById(role);
    }

    @Override
    public List<Long> selectPermissionIdsByRoleId(Long roleId) {
        return baseMapper.selectPermissionIdsByRoleId(roleId);
    }

    /**
     * 批量新增角色权限关联
     *
     * @param roleId        角色ID
     * @param permissionIds 权限ID数组
     */
    private void insertRolePermission(Long roleId, Long[] permissionIds) {
        List<RolePermission> list = new ArrayList<>();
        List<Long> permissionIdList = Arrays.asList(permissionIds);
        for (Long permissionId : permissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            list.add(rolePermission);
        }
        rolePermissionMapper.batchInsert(roleId, permissionIdList);
    }
}